import { showNotify, closeNotify } from 'vant';
import i18n from '@/utils/lang';
import system from '@/store/system';
import nocache from '@/store/nocache';
export declare interface instanceObject {
  [key: string]: string;
}

// 日期格式化
export const parseTime = (time: any, pattern?: string) => {
  if (!time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: any, key: any) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  });
  if(pattern === 'dateobject'){
    return Object.assign({}, formatObj, {
      m: String(formatObj.m).padStart(2, '0'),
      d: String(formatObj.d).padStart(2, '0'),
      h: String(formatObj.h).padStart(2, '0'),
      i: String(formatObj.i).padStart(2, '0'),
      s: String(formatObj.s).padStart(2, '0'),
    });
  }else{
    return time_str
  }
}

/**
 * JSON转url参数
 * @param data Json格式数据
 * */
export const formatJsonToUrlParams = (data: instanceObject) => {
  return typeof data === 'object'
    ? Object.keys(data)
        .map((key) => {
          return `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`;
        })
        .join('&')
    : '';
};

/**
 * 防抖
 * @param data Json格式数据
 * */
export const throttle = (callback: (v: any) => void, time: number) => {
  let timer: any = null;
  return function (v: any) {
    if(timer !== null){
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      callback(v);
    }, time * 1000);
  };
};


/**
 * 复制
 * @param content 复制内容
 * */
export const copy = (text: any) => {
  if (navigator.clipboard) {
    // clipboard api 复制
    navigator.clipboard.writeText(text);
  } else {
    var textarea = document.createElement('textarea');
    document.body.appendChild(textarea);
    // 隐藏此输入框
    textarea.style.position = 'fixed';
    textarea.style.clip = 'rect(0 0 0 0)';
    textarea.style.top = '10px';
    // 赋值
    textarea.value = text;
    // 选中
    textarea.select();
    // 复制
    document.execCommand('copy', true);
    // 移除输入框
    document.body.removeChild(textarea);
  }
  openNoticeMessage((i18n.global as any).t('login.success'));
};


/**
 * 通知栏
 * @param content 复制内容
 * */
export const openNoticeMessage = (text?: string, option?: any) => {
  if(text === "close"){
    closeNotify();
    ElMessage.closeAll();
    return false;
  }else{
    let opt:any = Object.assign({}, {
      type: 'success', // 消息的类型
      normal: true, // 是否普通消息
    }, option);
    const piniaSystem = system();
    if(window.Notification && /https:/i.test(document.location.protocol) && !opt.normal){
      const popNotice = function() {
        if (Notification.permission == "granted") {
          var notification = new Notification(String(text), {
            body: opt.content || '',
            icon: opt.icon || ''
          });
          notification.onclick = function() {
            notification.close();
          };
        }
      };
      if (Notification.permission == "granted") {
        popNotice();
      } else if (Notification.permission != "denied") {
        Notification.requestPermission(function (permission) {
          popNotice();
        });
      }
    }else{
      if(piniaSystem.getIsH5){
        showNotify({ type: opt.type, message: text });
      }else{
        ElMessage({
          type: opt.type,
          message: text,
        });
      }
    }
  }
};

/**
 * 隐藏昵称
 * @param text 昵称文本
 * */
export const handleHideName = (text: string) => {
  return text.slice(0, 2) + '****' + text.slice(text.length - 2);
};


/**
 * 下载图片
 * @param id 图片element的id
 * */
export const downloadImage = (id: string) => {
  const myCanvas:any = document.getElementById(id);
  const a = document.createElement('a');
  a.href = myCanvas.toDataURL('image/png');
  a.download = 'qrcode';
  a.click();
};


function loadScript (url:any) {
  return new Promise((resolve:any, reject:any) => {
    const script = document.createElement('script');
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`Load script from ${url} failed`));
    script.src = url;
    const head = document.head || document.getElementsByTagName('head')[0]
    ;(document.body || head).appendChild(script);
  })
}

//动态加载外部js
//@param RESOURCE_LIST 外部地址集合["address"]
export const loadVoLteResourceList = (RESOURCE_LIST:any, success?:any) => {
  return new Promise((r:any)=>{
    RESOURCE_LIST.reduce((res:any, el:any) => res.then(() => loadScript(el)), Promise.resolve()).then(() => {
      r();
    }).catch((error:any) => {
      console.error('前置js资源加载失败:', error.name, error.message);
      return Promise.reject(error);
    })
  })
}

// 触底检测
export const bottomingOut = (e:any) => {
  const piniaNocache = nocache();
  let st = window.pageYOffset || document.documentElement.scrollTop || e.target.scrollTop;
  let windowHeight = window.innerHeight || document.documentElement.clientHeight || e.target.clientHeight;
  let scrollHeight = e.target.scrollHeight;
  if(st + windowHeight >= scrollHeight - 50){
    console.log("触底222222222")
    // 触底
    piniaNocache.setHitBottom();
  }
}
